package com.peng.redis;

import com.peng.utils.JacksonUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.params.ScanParams;
import redis.clients.jedis.resps.ScanResult;

/**
 * JedisWithHashSample
 *
 * @author lupeng
 * Created on 2022-04-18
 */
public class JedisWithHashSample {

    private static final Logger logger = LoggerFactory.getLogger(JedisWithHashSample.class);

    private JedisPool pool;

    public static final String KEY = "hashkey";

    @BeforeEach
    public void init() {
        // pool = new JedisPool("localhost", 6379);
        // test-zhaopin01.rdb.58dns.org:50042
        // public JedisPool(GenericObjectPoolConfig<Jedis> poolConfig, String host, int port, int timeout, String password) {

        // zpad redis
        // pool = new JedisPool(new GenericObjectPoolConfig(), "test-zhaopin01.rdb.58dns.org", 50042, 10000, "208153357028f3f7");

        pool = new JedisPool(new GenericObjectPoolConfig(), "test-zhaopin05.rdb.58dns.org", 50090, 10000, "06643b881e175041");

        // decision redis
        // pool = new JedisPool(new GenericObjectPoolConfig(), "test-zhaopin01.rdb.58dns.org", 50090, 10000, "06643b881e175041");
        logger.info("JedisPool create success");
    }

    @AfterEach
    public void destroy() {
        if (pool != null) {
            pool.close();
        }
    }


    @Test
    public void t1() {
        try (Jedis jedis = pool.getResource()) {
            List<String> keyPrefix = new ArrayList<>();
            // keyPrefix.add("commerce-recall*");
            // keyPrefix.add("crlk*");
            // keyPrefix.add("gsclk*");
            // keyPrefix.add("crclk*");
            // keyPrefix.add("crarlk-*");
            // keyPrefix.add("crzddk-20240325*");
            // keyPrefix.add("commerce-recall-36*");
            // keyPrefix.add("msafrk*");
            //
            // // 清除实时弹窗的频控
            // keyPrefix.add("freq_con_user*");

            // AI外呼频控
            keyPrefix.add("msaatfk*");

            // 动作限流
            keyPrefix.add("msafrk-50422302848013*");
            keyPrefix.add("msafrk-97470302806076*");
            keyPrefix.add("msafrk-97470303121967*");
            keyPrefix.add("msafrk-97470302806076*");
            keyPrefix.add("msafrk-97223917541417*");
            keyPrefix.add("InfoCityCateImpl*");

            // String keyPattern = "getSubscribeReListByUserIdCache*";
            for (String keyPattern : keyPrefix) {
                Set<String> keys = jedis.keys(keyPattern);
                for (String key : keys) {
                    logger.info("[删除key: {}]", key);
                    jedis.del(key);
                }
            }
        }
    }

    @Test
    public void t11() {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)));
    }


    @Test
    public void hsetTest() {
        try (Jedis jedis = pool.getResource()) {
            long res = jedis.hset(KEY, "f1", "value1");
            jedis.pexpire(KEY, 9999);
            logger.info("res {}", res);
        }
    }

    /**
     * 只有当hash中的field不存在的时候才能设置成功
     */
    @Test
    public void hsetnxTest() {
        try (Jedis jedis = pool.getResource()) {
            long hsetnx = jedis.hsetnx(KEY, "f1", "val1");
            logger.info("hsetnx {}", hsetnx);

            long hsetnx1 = jedis.hsetnx(KEY, "f2", "val2");
            logger.info("hsetnx1 {}", hsetnx1);
        }
    }

    /**
     * 判断hash中指定的field是否存在
     */
    @Test
    public void hexistsTest() {
        try (Jedis jedis = pool.getResource()) {
            boolean hexists = jedis.hexists(KEY, "f1");
            logger.info("hexists {}", hexists);
        }
    }

    @Test
    public void hdelTest() {
        try (Jedis jedis = pool.getResource()) {
            long hdel = jedis.hdel(KEY, "f2");
            logger.info("hdel {}", hdel);
        }
    }

    /**
     * hlen 返回的是hash中key的个数
     */
    @Test
    public void hlenTest() {
        try (Jedis jedis = pool.getResource()) {
            String key = "hlenTestKey";
            Pipeline pipelined = jedis.pipelined();
            for (int i = 0; i < 100; i++) {
                pipelined.hset(key, i + "", i + "");
            }
            pipelined.pexpire(key, 99999);
            // 返回各个命令的执行结果
            List<Object> results = pipelined.syncAndReturnAll();
            logger.info("results {}", JacksonUtil.toJson(results));

            logger.info("hlen {}", jedis.hlen(key));
        }
    }

    @Test
    public void hstrlenTest() {
        try (Jedis jedis = pool.getResource()) {
            long hstrlen = jedis.hstrlen(KEY, "f1");
            logger.info("hstrlen {}", hstrlen);
        }
    }

    @Test
    public void hincrTest() {
        String key = "hlenTestKey";
        try (Jedis jedis = pool.getResource()) {
            long res = jedis.hincrBy(key, "1", 11);
            logger.info("hstrlen {}", res);
        }
    }

    @Test
    public void hmsetTest() {
        String key = "hlenTestKey";
        Map<String, String> fieldValueMap = new HashMap<>();
        for (int i = 0; i < 100; i++) {
            fieldValueMap.put(String.valueOf(i), String.valueOf(i));
        }
        try (Jedis jedis = pool.getResource()) {
            String hmset = jedis.hmset(key, fieldValueMap);
            logger.info("hmset {}", hmset);
        }
    }

    @Test
    public void hmgetTest() {
        String key = "hlenTestKey";
        List<String> fields = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            fields.add(String.valueOf(i));
        }
        try (Jedis jedis = pool.getResource()) {
            List<String> hmget = jedis.hmget(key, fields.toArray(new String[0]));
            logger.info("hmget {}", hmget);
        }
    }

    @Test
    public void hkeysTest() {
        String key = "hlenTestKey";
        try (Jedis jedis = pool.getResource()) {
            Set<String> hkeys = jedis.hkeys(key);
            logger.info("hkeys {}", JacksonUtil.toJson(hkeys));
        }
    }

    @Test
    public void hvalsTest() {
        String key = "hlenTestKey";
        try (Jedis jedis = pool.getResource()) {
            List<String> hvals = jedis.hvals(key);
            logger.info("hvals {}", JacksonUtil.toJson(hvals));
        }
    }

    @Test
    public void hgetallTest() {
        String key = "hlenTestKey";
        try (Jedis jedis = pool.getResource()) {
            Map<String, String> hgetAll = jedis.hgetAll(key);
            logger.info("hgetAll {}", JacksonUtil.toJson(hgetAll));
        }
    }

    @Test
    public void hscanTest() {
        String key = "hlenTestKey";
        try (Jedis jedis = pool.getResource()) {
            Map<String, String> hmset = new HashMap<>();
            for (int i = 0; i < 9999; i++) {
                hmset.put(String.valueOf(i), i + "val");
            }
            jedis.hmset(key, hmset);

            ScanParams scanParams = new ScanParams().count(5).match("*2*");
            String cursor = "0";
            do {
                ScanResult<Map.Entry<String, String>> hscan = jedis.hscan(key, cursor, scanParams);
                List<Map.Entry<String, String>> result = hscan.getResult();
                String nextCursor = hscan.getCursor();
                cursor = nextCursor;
                logger.info("cursor {}", nextCursor);
                logger.info("result {}", JacksonUtil.toJson(result));
            } while (!StringUtils.equals(cursor, "0"));
        }
    }


    @Test
    public void t111() {
        List<Integer> list = new ArrayList<>();
        list.add(5452);
        list.add(5672);
        list.add(5964);
        list.add(5616);
        list.add(6090);
        list.add(8828);
        list.add(8512);
        list.add(8564);
        list.add(9303);
        list.add(9550);
        list.add(6037);
        list.add(5691);
        list.add(8883);
        list.add(5893);
        list.add(8549);
        list.add(5681);
        list.add(9245);
        list.add(8648);
        list.add(5664);
        list.add(8786);
        list.add(5942);
        list.add(9387);
        list.add(5915);
        list.add(5949);
        list.add(9378);
        list.add(9326);
        list.add(6085);
        list.add(9166);
        list.add(6068);
        list.add(6048);
        list.add(8854);
        list.add(9259);
        list.add(6044);
        list.add(6121);
        list.add(9611);
        list.add(5883);
        list.add(9498);
        list.add(8905);
        list.add(5727);
        list.add(5900);
        list.add(8858);
        list.add(9429);
        list.add(5843);
        list.add(8846);
        list.add(5784);
        list.add(8506);
        list.add(5552);
        list.add(8716);
        list.add(5687);
        list.add(8991);

        int sum = 0;
        for (Integer integer : list) {
            sum += integer;
        }
        System.out.println(sum);
    }


    @Test
    public void t1112() {
        List<Person> ps = new ArrayList<>();
        // List<Person> ps = null;
        ps.add(null);
        // ps.add(new Person(null));
        Set<Integer> collect = ps.stream()
                .map(Person::getId)
                .collect(Collectors.toSet());
        System.out.println(collect);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Person {
        private Integer id;
    }


}
